package com.example.myapplication.ui.screen

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.example.myapplication.network.api.ProductDetail
import com.example.myapplication.network.core.NetworkResult
import com.example.myapplication.ui.common.ErrorContent
import com.example.myapplication.ui.common.LoadingContent
import com.example.myapplication.ui.viewmodel.ProductDetailViewModel

@Composable
fun ProductDetailScreen(
    navController: NavController,
    viewModel: ProductDetailViewModel = viewModel()
) {
    val productDetailState = viewModel.productDetailState.collectAsState()

    when (val state = productDetailState.value) {
        is NetworkResult.Loading<*> -> LoadingContent()
        is NetworkResult.Error<*> -> ErrorContent()
        is NetworkResult.Success<ProductDetail> -> ProductDetailContent(navController, state.data)
    }
}

@Composable
fun ProductDetailContent(navController: NavController, productDetail: ProductDetail) {

    //设置滑动页的数量
    val pagerState = rememberPagerState(pageCount = { productDetail.spu.imageList.size }) // 页数为 5

    //获取所有sku中价格最低的SKU数据
    val sku = remember(productDetail){
        productDetail.skus.minBy { sku -> sku.price }
    }

    //将sku转换为和selectedSpecs集合对应的键值数据
    val defaultSelectedSpecs =  remember(sku) {
        sku.specValues.associate { it.specId to it.id } ?: emptyMap()
    }

    //记录当前规则选中器选中的规格维度id和其对对应的规格值id
    //假设：颜色的规格Id为：1, 容量的规格id为: 2
    //保存选中的规格值（可变 Map）举例：<1,1>  <2,5>
    val selectedSpecs = remember { mutableStateMapOf<Int, Int>() }

    //把默认最小价格的sku对<specId,specValueId> 存入 selectedSpecs
    //组件一进来，初始化时将defaultSelectedSpecs添加到selectedSpecs中
    LaunchedEffect(defaultSelectedSpecs) {
        selectedSpecs.putAll(defaultSelectedSpecs)
    }

    //匹配选中的SKU
    var currentSku = remember(selectedSpecs.toMap()) {
        //查找满足条件的sku(选中的SKU)
        productDetail.skus.firstOrNull{sku->
            //把所有sku按照条件转好为Map
            var selected = sku.specValues.associate { it.specId to it.id }
            selected == selectedSpecs
        }
    }

    Column(
        modifier = Modifier.fillMaxSize(),
        horizontalAlignment = Alignment.Start
    ) {
        //顶部返回键
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
        ) {
            IconButton(onClick = {
                navController.popBackStack()    //返回
            }) {
                Icon(
                    imageVector = Icons.AutoMirrored.Default.ArrowBack,
                    contentDescription = "返回键",
                    tint = Color.Black
                )
            }
        }

        //使用Pager显示商品图片
        HorizontalPager(pagerState) { page ->
            AsyncImage(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(300.dp),
                model = productDetail.spu.imageList[page],
                contentDescription = "商品详情图片",
                contentScale = ContentScale.Crop
            )
        }


        Column(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1F)
                .padding(8.dp)
        ) {
            //商品的描述、标题等
            Text(
                text = productDetail.spu.title + productDetail.spu.description + productDetail.spu.subTitle,
                fontSize = 20.sp,
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )

            //价格和库存
            Text(
                text = "价格：${currentSku?.price}",
                fontSize = 30.sp,
                color = Color.Red
            )

            Text(
                text = "库存：${currentSku?.stock}",
                fontSize = 18.sp,
                color = Color.Black
            )

            //显示规格选择器
            productDetail.specs.forEach { spec ->
                val specName = spec.name    //规格维度名称（颜色、存储容量）
                Column {
                    Text(
                        text = specName
                    )

                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(10.dp, Alignment.Start)
                    ) {
                        spec.values.forEach { specValue ->

                            SpecValueChip(
                                text = specValue.value,
                                selected = selectedSpecs[spec.id] == specValue.id,
                                onClick = {
                                    //<颜色,深空黑>  <容量,128G>
                                    selectedSpecs[spec.id] = specValue.id
                                },
                                modify = Modifier
                            )
                        }
                    }
                }
            }

            Button(onClick = {
                //把该SKU的信息添加到购物车的数据库中 POST请求。

            }) {
                Text("加入购物车")
            }
        }
    }
}


@Composable
fun SpecValueChip(
    text: String,
    selected: Boolean, //是否被选中的状态
    onClick: () -> Unit,
    modify: Modifier
) {
    Box(
        contentAlignment = Alignment.Center,
        modifier = modify
            .background(color = if (selected) Color(0xFF4974C6) else Color(0xFFE2E0E3), shape = RoundedCornerShape(50))
            .clip(shape = RoundedCornerShape(50))
            .padding(vertical = 5.dp, horizontal = 10.dp)
            .clickable(onClick = {
                onClick()
            })
    ) {
        Text(
            text = text,
            color = if (selected) Color.White else Color.White
        )
    }
}
